package com.dhy.dbCore.dataSource;

import com.dhy.dbCore.transaction.util.ConnectionHolder;
import com.dhy.dbCore.transaction.util.TransactionResourceManager;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author 大忽悠
 * @create 2022/6/6 20:28
 */
public class DataSourceUtils {

    public static Connection getConnection(DataSource dataSource){
        ConnectionHolder connectionHolder = TransactionResourceManager.getResource();
        Connection conn = null;
        if (connectionHolder != null && (conn = connectionHolder.getConnection()) != null) {
             return conn;
        }
        try {
            conn = dataSource.getConnection();
            TransactionResourceManager.bindResource(new ConnectionHolder(conn));
            return conn;
        } catch (SQLException e) {
            throw new RuntimeException("获取数据库连接失败: ",e);
        }
    }
}
